"use client"

import {useState} from "react"
import {useAppStore} from "@/lib/store"
import {Card, CardContent} from "@/components/ui/card"
import {Checkbox} from "@/components/ui/checkbox"
import {Button} from "@/components/ui/button"
import {Badge} from "@/components/ui/badge"
import {ScrollArea} from "@/components/ui/scroll-area"
import {Collapsible, CollapsibleContent} from "@/components/ui/collapsible"
import {ChevronDown, ChevronRight, Code, Edit, Trash2} from "lucide-react"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog"
import {Label} from "@/components/ui/label"
import {Input} from "@/components/ui/input"
import {Textarea} from "@/components/ui/textarea"
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select"

export function TodoList() {
    const {todoList, toggleTodoSelection, updateTodoItem, removeTodoItem} = useAppStore()
    const [editingTodo, setEditingTodo] = useState<number | null>(null)
    const [editForm, setEditForm] = useState({
        title: "",
        description: "",
        priority: "medium" as "high" | "medium" | "low",
    })
    const [expandedItems, setExpandedItems] = useState<Set<number>>(new Set())
    const [viewingCode, setViewingCode] = useState<number | null>(null)

    const toggleExpand = (id: number) => {
        const newExpanded = new Set(expandedItems)
        if (newExpanded.has(id)) {
            newExpanded.delete(id)
        } else {
            newExpanded.add(id)
        }
        setExpandedItems(newExpanded)
    }

    const handleEditClick = (id: number) => {
        const todo = todoList.find((t) => t.id === id)
        if (todo) {
            setEditForm({
                title: todo.title,
                description: todo.description,
                priority: todo.priority,
            })
            setEditingTodo(id)
        }
    }

    const handleSaveEdit = () => {
        if (editingTodo) {
            updateTodoItem(editingTodo, {
                title: editForm.title,
                description: editForm.description,
                priority: editForm.priority,
            })
            setEditingTodo(null)
        }
    }

    const getPriorityColor = (priority: string) => {
        switch (priority) {
            case "high":
                return "bg-red-100 text-red-800 hover:bg-red-200"
            case "medium":
                return "bg-yellow-100 text-yellow-800 hover:bg-yellow-200"
            case "low":
                return "bg-green-100 text-green-800 hover:bg-green-200"
            default:
                return "bg-gray-100 text-gray-800 hover:bg-gray-200"
        }
    }

    const getStatusColor = (status: string) => {
        switch (status) {
            case "done":
                return "bg-green-100 text-green-800"
            case "in-progress":
                return "bg-blue-100 text-blue-800"
            case "todo":
            default:
                return "bg-gray-100 text-gray-800"
        }
    }

    const getStatusText = (status: string) => {
        switch (status) {
            case "done":
                return "已完成"
            case "in-progress":
                return "进行中"
            case "todo":
            default:
                return "待处理"
        }
    }

    return (
        <div className="space-y-4">
            <ScrollArea className="h-[400px]">
                <div className="space-y-2 pr-4">
                    {todoList.map((todo) => (
                        <Card key={todo.id} className={`border ${todo.selected ? "border-primary" : ""}`}>
                            <CardContent className="p-4">
                                <div className="flex items-start space-x-2">
                                    <Checkbox
                                        checked={todo.selected}
                                        onCheckedChange={() => toggleTodoSelection(todo.id)}
                                        className="mt-1"
                                    />
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center justify-between">
                                            <div className="flex items-center space-x-2">
                                                <Button variant="ghost" size="sm" className="h-6 w-6 p-0"
                                                        onClick={() => toggleExpand(todo.id)}>
                                                    {expandedItems.has(todo.id) ? (
                                                        <ChevronDown className="h-4 w-4"/>
                                                    ) : (
                                                        <ChevronRight className="h-4 w-4"/>
                                                    )}
                                                </Button>
                                                <h3 className="font-medium truncate">{todo.title}</h3>
                                            </div>
                                            <div className="flex items-center space-x-2">
                                                <Badge className={getPriorityColor(todo.priority)}>
                                                    {todo.priority === "high" ? "高" : todo.priority === "medium" ? "中" : "低"}
                                                </Badge>
                                                <Badge
                                                    className={getStatusColor(todo.status)}>{getStatusText(todo.status)}</Badge>
                                            </div>
                                        </div>

                                        <Collapsible open={expandedItems.has(todo.id)}>
                                            <CollapsibleContent className="mt-2 space-y-2">
                                                <p className="text-sm text-gray-600">{todo.description}</p>

                                                <div className="flex justify-between items-center pt-2">
                                                    <div className="flex space-x-2">
                                                        <Dialog>
                                                            <DialogTrigger asChild>
                                                                <Button variant="outline" size="sm"
                                                                        onClick={() => handleEditClick(todo.id)}>
                                                                    <Edit className="h-3.5 w-3.5 mr-1"/>
                                                                    编辑
                                                                </Button>
                                                            </DialogTrigger>
                                                            <DialogContent>
                                                                <DialogHeader>
                                                                    <DialogTitle>编辑任务</DialogTitle>
                                                                    <DialogDescription>修改任务的标题、描述和优先级</DialogDescription>
                                                                </DialogHeader>
                                                                <div className="space-y-4 py-4">
                                                                    <div className="space-y-2">
                                                                        <Label htmlFor="title">标题</Label>
                                                                        <Input
                                                                            id="title"
                                                                            value={editForm.title}
                                                                            onChange={(e) => setEditForm({
                                                                                ...editForm,
                                                                                title: e.target.value
                                                                            })}
                                                                        />
                                                                    </div>
                                                                    <div className="space-y-2">
                                                                        <Label htmlFor="description">描述</Label>
                                                                        <Textarea
                                                                            id="description"
                                                                            value={editForm.description}
                                                                            onChange={(e) => setEditForm({
                                                                                ...editForm,
                                                                                description: e.target.value
                                                                            })}
                                                                            rows={4}
                                                                        />
                                                                    </div>
                                                                    <div className="space-y-2">
                                                                        <Label htmlFor="priority">优先级</Label>
                                                                        <Select
                                                                            value={editForm.priority}
                                                                            onValueChange={(value) => setEditForm({
                                                                                ...editForm,
                                                                                priority: value as any
                                                                            })}
                                                                        >
                                                                            <SelectTrigger>
                                                                                <SelectValue placeholder="选择优先级"/>
                                                                            </SelectTrigger>
                                                                            <SelectContent>
                                                                                <SelectItem value="high">高</SelectItem>
                                                                                <SelectItem
                                                                                    value="medium">中</SelectItem>
                                                                                <SelectItem value="low">低</SelectItem>
                                                                            </SelectContent>
                                                                        </Select>
                                                                    </div>
                                                                </div>
                                                                <DialogFooter>
                                                                    <Button variant="outline"
                                                                            onClick={() => setEditingTodo(null)}>
                                                                        取消
                                                                    </Button>
                                                                    <Button onClick={handleSaveEdit}>保存</Button>
                                                                </DialogFooter>
                                                            </DialogContent>
                                                        </Dialog>

                                                        <Button
                                                            variant="outline"
                                                            size="sm"
                                                            className="text-destructive hover:text-destructive hover:bg-destructive/10"
                                                            onClick={() => removeTodoItem(todo.id)}
                                                        >
                                                            <Trash2 className="h-3.5 w-3.5 mr-1"/>
                                                            删除
                                                        </Button>
                                                    </div>

                                                    {todo.generatedCode && (
                                                        <Dialog>
                                                            <DialogTrigger asChild>
                                                                <Button variant="outline" size="sm"
                                                                        onClick={() => setViewingCode(todo.id)}>
                                                                    <Code className="h-3.5 w-3.5 mr-1"/>
                                                                    查看代码
                                                                </Button>
                                                            </DialogTrigger>
                                                            <DialogContent className="max-w-3xl">
                                                                <DialogHeader>
                                                                    <DialogTitle>{todo.title} - 生成的代码</DialogTitle>
                                                                </DialogHeader>
                                                                <ScrollArea className="h-[500px] w-full">
                                  <pre className="p-4 bg-muted rounded-md text-sm font-mono whitespace-pre-wrap">
                                    {todo.generatedCode}
                                  </pre>
                                                                </ScrollArea>
                                                            </DialogContent>
                                                        </Dialog>
                                                    )}
                                                </div>
                                            </CollapsibleContent>
                                        </Collapsible>
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    ))}
                </div>
            </ScrollArea>
        </div>
    )
}
